package com.onegroup.filter;

import com.onegroup.common.enums.ResponseStatusEnum;
import com.onegroup.common.exception.MyCustomException;
import com.onegroup.common.utils.JwtUtil;
import com.onegroup.common.utils.RedisCache;
import com.onegroup.pojo.dto.ApplicationDto;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author: 曾雪斌
 * @Description: OncePerRequestFilter只走一次,在请求前
 * @History:
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }

        // 解析token
        String appId;
        try {
            Claims claims = JwtUtil.parseJwt(token);
            appId = claims.getSubject();
        } catch (Exception e) {
            throw new MyCustomException(ResponseStatusEnum.TOKEN_ERROR);
        }

        // 获取userId redis获取用户信息
        ApplicationDto applicationDto = redisCache.getCacheObject("login:application:" + appId);
        System.out.println(applicationDto);
        if (Objects.isNull(applicationDto)) {
            throw new MyCustomException(ResponseStatusEnum.NOT_LOGIN);
        }

        // 封装Authentication
        UsernamePasswordAuthenticationToken auth
                = new UsernamePasswordAuthenticationToken(applicationDto,
                null,
                applicationDto.getAuthorities());

        // 存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(auth);

        // 放行
        filterChain.doFilter(request, response);
    }
}
